package com.jbwz.web.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jbwz.web.common.base.BaseServiceImpl;
import com.jbwz.web.common.base.IBasePage;
import com.jbwz.web.common.exception.BusinessException;
import com.jbwz.web.common.res.ResponseCodeBase;
import com.jbwz.web.common.util.BeanUtilCommon;
import com.jbwz.web.security.entity.Company;
import com.jbwz.web.security.entity.vo.CompanyVO;
import com.jbwz.web.security.mapper.CompanyMapper;
import com.jbwz.web.security.service.CompanyService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 公司 服务实现类
 * </p>
 *
 * @author yyh
 * @since 2021-08-23 22:44:42
 */
@Service
public class CompanyServiceImpl extends BaseServiceImpl<CompanyMapper, Company> implements CompanyService {

    @Override
    public IBasePage pageList(IBasePage page, CompanyVO vo) {
        QueryWrapper<Company> query = Wrappers.<Company>query().like(StringUtils.hasText(vo.getName()), "name", vo.getName());
        IBasePage<Company> p = baseMapper.selectPage(page, query);
        return p.convert(this::toVO);
    }

    public CompanyVO toVO(Company e) {
        CompanyVO companyVO = new CompanyVO();
        BeanUtilCommon.copy(e, companyVO);
        return companyVO;
    }

    @Override
    public Company saveValidate(CompanyVO vo) {
        Company company = toEntity(vo);
        checkName(company);
        saveOrUpdate(company);
        return company;
    }

    private Company toEntity(CompanyVO vo) {
        Company copy = BeanUtilCommon.copy(vo, new Company());
        return copy;
    }

    @Override
    public Optional<Company> getByName(String name) {
        Company one = this.getOne(Wrappers.<Company>query().eq("name", name));
        return Optional.ofNullable(one);
    }

    private void checkName(Company company) {
        Optional<Company> byName = getByName(company.getName());
        if (byName.isPresent()) {
            if (Objects.isNull(company.getId()) || !company.getId().equals(byName.get().getId()))
                throw BusinessException.resMsg(ResponseCodeBase.dataExist.withMsg("公司名称已存在"));
        }
    }

}
